<?php

include_once('cfg/cfg.php');
include_once("utils.class.php");
include_once("smtp.class.php");

class Mailer
{
	public static function send($addr_array, $subj, $body, $from = null)
	{
		if(is_null($from)) $from = MAIL_FROM;
		
		// return TRUE;
		if(USE_SMTP)
		{
			return self::send_smtp($addr_array, $subj, $body, $from);
		}
		else
		{
			$headers  = "From: $from\n";
			$headers .= "Content-Type: text/html; charset=UTF-8\n";
			$headers .= "Content-Transfer-Encoding: 8bit\n";
			
			$header = "Content-Type: text/html; charset=utf-8\n";
			$header .= "From: $from\n";
			return mail(implode(",", $addr_array), $subj, $body, $header);
		}
	}
	
	private static function send_smtp($addrs, $subj, $body, $from = null)
	{
		global $smtpurl;
		
        try
		{
			$params = Utils::parse_url2($smtpurl);
            $smtp = new SMTP(
				$params['host'],
				$params['port'],
				$params['helo'],
				true,
				$params['user'],
				$params['pass']
			);
            $smtp->dbug = FALSE;
			
			if(is_null($from)) $from = $params['from'];
			
            $x = $smtp->Connect();
            $x = $smtp->Send($addrs,     // Array of recipient addresses
                        $from,           // SMTP From address
                        array(
                            'Date' => date("D, j M Y G:i:s")." +0700",
                            'X-Mailer' => 'The Bat! (v3.99.3) Professional',
                            'X-Priority' => '3 (Normal)',
                            'Message-ID' => '<172562218.'.date("YmjHis").'@mail.ru>',
                            'Subject' => $subj,
                            'MIME-Version' => '1.0',
                            'Content-type' => 'text/html; charset=utf-8'
                            ),   // The emails headers
                        $body);   // The emails body (phwoar...)
			return TRUE;
        }
		catch (Exception $e)
		{
			$msg = $e->GetMessage();
			Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, "ERROR: $msg");
			return FALSE;
        }
	}
}
